import os

from src.simulation_system.trafficlight import TrafficLight
from src.simulation_system.unity_manager import UnityManager
from src.sumo_simulation.sumo_manager import SumoSimulation

ip = "localhost"
port = 54321


class ScenarioManager:
    """
    The Scenario manager for co-simulation(Unity-SUMO).
    """

    def __init__(self, cav_world, sumo_cfg=None, unity=True):
        self.cav_world = cav_world
        self._depart_vehicles = []
        self._arrive_vehicles = []

        assert os.path.isfile(sumo_cfg), '%s does not exist, make sure' \
                                         'your config file name has the' \
                                         'same basename as the directory' \
                                         'and use .sumocfg as extension' \
                                         % sumo_cfg
        self.sumo = SumoSimulation(sumo_cfg)
        trafficlight_ids = self.sumo.get_trafficlights()
        for trafficlight_id in trafficlight_ids:
            self.cav_world.add_trafficlight(TrafficLight(trafficlight_id))

        if unity:
            self.server = UnityManager(cav_world)

    def tick(self):

        self.sumo.tick()
        self._depart_vehicles = self.sumo.get_depart_vehicles()
        self._arrive_vehicles = self.sumo.get_arrive_vehicles()
        # Sumo vehicles sync to system
        for depart_vehicle in self._depart_vehicles:
            self.cav_world.add_vehicle(depart_vehicle)
        for arrive_vehicle in self._arrive_vehicles:
            self.cav_world.destroy_vehicle(arrive_vehicle)

        # self.cav_world.update_trafficlight()

    def close(self):
        """
        Simulation close.
        """
        self.sumo.close()
